<?php
namespace Admin\Controller;
use Think\Controller;
class ReportController extends Controller {
    public function getChilds($data,$uid,$arr){//获所有下级，只有账号
        foreach ($data as $k => $v){
            if($uid==$v['user_recommend']){
                unset($data[$k]);
                $arr[]=$v['user_id'];
                $arr=$this->getChilds($data,$v['user_id'],$arr);
            }
        }
        return $arr;
    }

    public function getChildsClass($data,$uid,$arr,$n){//获取下线层级
        $n++;
        foreach ($data as $k => $v){
            if($uid==$v['user_recommend']){
                $v['class']=$n;
                $arr[]=$v;
                unset($data[$k]);
                $arr=$this->getChildsClass($data,$v['user_id'],$arr,$n);
            }
        }
        return $arr;
    }

    public function index(){//团队管理
        $admin = session('admin');
        if(empty($admin)){echo "身份信息过期请重新登录";exit;}
        $id=I('id');
        if(!empty($id)){
            set_time_limit(120);//程序执行时间
            $type=I('post.type') ? I('post.type') : 1;
            $model=M('user');
            $user=$model->field('user.user_id,user.user_recommend,user.user_name,user.user_email,user.user_phone,user.user_createtime,user.level,position.user_position')
                ->join('position ON user.position = position.id','left')->where(['user.user_id'=>$id])->find();
            $uid_arr[]=$id;
            $arr[]=$user;
            $list[]=$user;
            if($type==2){//查询团队
                $from=I('post.from') ? I('post.from') : 0;
                $to=I('post.to') ? I('post.to') : 0;
                if(!empty($from) && !empty($to)){
                    $users=$model->field('user.user_id,user.user_recommend,user.user_name,user.user_email,user.user_phone,user.user_createtime,user.level,position.user_position')
                        ->join('position ON user.position = position.id','left')
                        ->where('(user.user_createtime between \''.$from.'\' and \''.$to.' 23:59:59\') and (user.user_recommend >0)')->select();
                    $this->assign('from',$from);
                    $this->assign('to',$to);
                }else{
                    $users=$model->field('user.user_id,user.user_recommend,user.user_name,user.user_email,user.user_phone,user.user_createtime,user.level,position.user_position')
                        ->join('position ON user.position = position.id','left')->where('user.user_recommend >0')->select();
                }
                $childrenFile='Uploads/getChildsClass-group/'.date('Ymd').'-'.$id.'.txt';
                if(file_exists($childrenFile)){//判断更新缓存
                    $children=file_get_contents($childrenFile);
                    $list=unserialize($children);
                }else{
                    set_time_limit(120);//程序执行时间
                    $list=$this->getChildsClass($users,$id,$arr,0);
                    $childrenData=serialize($list);
                    file_put_contents($childrenFile,$childrenData);
                    //$this->ajaxReturn(array('status'=>0,'msg'=>'缓存信息已更新，请重新载入'));
                }
                foreach ($list as $k => $v){
                    $uid_arr[]=$v['user_id'];
                }
            }
            $section=C('section');//获取号段
            $model=M('mt4_trades','','DB_CONFIG2');
            $where='(CMD between 0 and 1) and (LOGIN between '.$section['min'].' and '.$section['max'].')';// and (LOGIN in ('.implode(',',$uid_arr).'))
            $standard=[];//外汇交易
            $reoups_standard=$model->field('LOGIN,sum(VOLUME)')->where($where.' and (right(SYMBOL,2) <> \'bo\')')->group('LOGIN')->select();//外汇交易
            foreach ($reoups_standard as $k => $v){
                if(in_array($v['login'],$uid_arr)){
                    $standard[$v['login']]=round($v['sum(volume)']/100,2);
                }
            }
            $rapidly=[];//短期交易
            $reoups_rapidly=$model->field('LOGIN,sum(VOLUME)')->where($where.' and (right(SYMBOL,2) = \'bo\')')->group('LOGIN')->select();//短期交易
            foreach ($reoups_rapidly as $k => $v){
                if(in_array($v['login'],$uid_arr)){
                    $rapidly[$v['login']]=intval($v['sum(volume)']/100);
                }
            }
            $blance=[];//查询余额
            $user_blance=M('mt4_users','','DB_CONFIG2')->field('LOGIN,BALANCE')->where('LOGIN between '.$section['min'].' and '.$section['max'])->select();//查询余额
			//print_r($user_blance);die;
            foreach ($user_blance as $k => $v){
                if(in_array($v['login'],$uid_arr)){
                    $blance[$v['login']]=$v['balance'];
                }
            }
            foreach ($list as $k => $v){
                $list[$k]['standard']=$standard[$v['user_id']];
                $list[$k]['rapidly']=$rapidly[$v['user_id']];
                $list[$k]['balance']=$blance[$v['user_id']];
            }
            //$this->ajaxReturn(array('status'=>1,'msg'=>$list));
            $this->assign('type',$type);
            $this->assign('id',$id);
            $this->assign('list',$list);
        }
        $this->display();
    }

    public function downloadGroup(){//搜索团队
        $admin = session('admin');
        if(empty($admin)){echo "身份信息过期请重新登录";exit;}
        $id=I('id');
        $list=[];
        if(!empty($id)){
            set_time_limit(120);//程序执行时间
            $type=I('type') ? I('type') : 1;
            $model=M('user');
            $user=$model->field('user.user_id,user.user_name,user.user_recommend,user.user_email,user.user_phone,user.level,position.user_position')
                ->join('position ON user.position = position.id','left')->where(['user.user_id'=>$id])->find();
            $uid_arr=[];
            $arr[]=$user;
            $list=$user;
            if($type==2){//查询团队
                $from=I('from') ? I('from') : 0;
                $to=I('to') ? I('to') : 0;
                if(!empty($from) && !empty($to)){
                    $users=$model->field('user.user_id,user.user_name,user.user_recommend,user.user_email,user.user_phone,user.level,position.user_position')
                        ->join('position ON user.position = position.id','left')
                        ->where('(user.user_createtime between \''.$from.'\' and \''.$to.' 23:59:59\') and (user.user_recommend >0)')->select();
                    $this->assign('from',$from);
                    $this->assign('to',$to);
                }else{
                    $users=$model->field('user.user_id,user.user_name,user.user_recommend,user.user_email,user.user_phone,user.level,position.user_position')
                        ->join('position ON user.position = position.id','left')->where('user.user_recommend >0')->select();
                }
                $childrenFile='Uploads/getChildsClass-group/'.date('Ymd').'-'.$id.'.txt';
                if(file_exists($childrenFile)){//判断更新缓存
                    $children=file_get_contents($childrenFile);
                    $list=unserialize($children);
                }else{
                    set_time_limit(120);//程序执行时间
                    $list=$this->getChildsClass($users,$id,$arr,0);
                    $childrenData=serialize($list);
                    file_put_contents($childrenFile,$childrenData);
                    //$this->ajaxReturn(array('status'=>0,'msg'=>'缓存信息已更新，请重新载入'));
                }
                foreach ($list as $k => $v){
                    $uid_arr[]=$v['user_id'];
                }
            }
            $section=C('section');//获取号段
            $model=M('mt4_trades','','DB_CONFIG2');
            $where='(CMD between 0 and 1) and (LOGIN between '.$section['min'].' and '.$section['max'].')';// and (LOGIN in ('.implode(',',$uid_arr).'))
            $standard=[];//外汇交易
            $reoups_standard=$model->field('LOGIN,sum(VOLUME)')->where($where.' and (right(SYMBOL,2) <> \'bo\')')->group('LOGIN')->select();//外汇交易
            foreach ($reoups_standard as $k => $v){
                if(in_array($v['login'],$uid_arr)){
                    $standard[$v['login']]=round($v['sum(volume)']/100,2);
                }
            }
            $rapidly=[];//短期交易
            $reoups_rapidly=$model->field('LOGIN,sum(VOLUME)')->where($where.' and (right(SYMBOL,2) = \'bo\')')->group('LOGIN')->select();//短期交易
            foreach ($reoups_rapidly as $k => $v){
                if(in_array($v['login'],$uid_arr)){
                    $rapidly[$v['login']]=intval($v['sum(volume)']/100);
                }
            }
            $blance=[];//查询余额
            $user_blance=M('mt4_users','','DB_CONFIG2')->field('LOGIN,BALANCE')->where($where)->select();//查询余额
            foreach ($user_blance as $k => $v){
                if(in_array($v['login'],$uid_arr)){
                    $blance[$v['login']]=$v['balance'];
                }
            }
            foreach ($list as $k => $v){
                $list[$k]['standard']=$standard[$v['user_id']];
                $list[$k]['rapidly']=$rapidly[$v['user_id']];
                $list[$k]['balance']=$blance[$v['user_id']];
            }
        }
        $csv=new \Think\Csv();
        $csv_title=array('MT4','姓名','代理人','邮箱','电话','杠杆','职位','层级','外汇交易量','短期交易量','余额');
        $csv->put_csv($list,$csv_title);
    }

    public function history(){//交易历史
        $admin = session('admin');
        if(empty($admin)){echo "身份信息过期请重新登录";exit;}
        $id=I('id');
        if(!empty($id)){
            $from=I('from') ? I('from') : 0;
            $to=I('to') ? I('to') : 0;
            $transaction_type=I('transaction_type') ? I('transaction_type') : 0;
            $type=I('type') ? I('type') : 1;
            if($type==1){
                $where='(CMD between 0 and 1) and (LOGIN = '.$id.') ';
            }else{
                set_time_limit(120);//程序执行时间
                $users=M('user')->field('user_id,user_recommend')->where('user_recommend > 0')->select();
                $childrenFile='Uploads/getChilds/'.date('Ymd').'-'.$id.'.txt';
                if(file_exists($childrenFile)){//判断更新缓存
                    $children=file_get_contents($childrenFile);
                    $login=unserialize($children);
                }else{
                    $arr[]=$id;
                    set_time_limit(120);//程序执行时间
                    $login=$this->getChilds($users,$id,$arr);
                    $childrenData=serialize($login);
                    file_put_contents($childrenFile,$childrenData);
                    //$this->ajaxReturn(array('status'=>0,'msg'=>'缓存信息已更新，请重新载入'));
                }
                $where='(CMD between 0 and 1) and (LOGIN in ('.implode(',',$login).')) ';
            }
            if($transaction_type==1){
                $where.=' and (right(SYMBOL,2) = \'bo\') ';
            }else if($transaction_type==2){
                $where.=' and (right(SYMBOL,2) <> \'bo\') ';
            }
            if(!empty($from) && !empty($to)){
                $where.=' and (CLOSE_TIME between \''.$from.' 00:00:00\' and \''.$to.' 23:59:59\') ';
                $this->assign('from',$from);
                $this->assign('to',$to);
            }
            $model=M('mt4_trades','','DB_CONFIG2');
            $count=$model->where($where)->count();
            $Page = new \Think\Page($count,25);
            $Page->parameter['id']=$id;
            $Page->parameter['transaction_type']=$transaction_type;
            $Page->parameter['type']=$type;
            $Page->parameter['from']=$from;
            $Page->parameter['to']=$to;
            $show = $Page->show();
            $reoups=$model->field('TICKET,LOGIN,OPEN_TIME,CMD,SYMBOL,VOLUME,OPEN_PRICE,SL,TP,CLOSE_TIME,CLOSE_PRICE,COMMISSION,SWAPS,PROFIT,COMMENT')
                ->where($where)->order('TICKET desc')->limit($Page->firstRow.','.$Page->listRows)->select();
            $sum=$model->field('sum(VOLUME),sum(COMMISSION),sum(SWAPS),sum(PROFIT)')->where($where)->find();
            $this->assign('sum',$sum);
            $this->assign('list',$reoups);
            $this->assign('page',$show);
            $this->assign('transaction_type',$transaction_type);
            $this->assign('type',$type);
            $this->assign('id',$id);
        }
        $this->display();
    }

    public function downloadHistory(){//下载交易明细
        $admin = session('admin');
        if(empty($admin)){echo "身份信息过期请重新登录";exit;}
        $id=I('id');
        $list=[];
        if(!empty($id)){
            $from=I('from') ? I('from') : 0;
            $to=I('to') ? I('to') : 0;
            $transaction_type=I('transaction_type') ? I('transaction_type') : 0;
            $type=I('type') ? I('type') : 1;
            if($type==1){
                $where='(CMD between 0 and 1) and (LOGIN = '.$id.') ';
            }else{
                set_time_limit(120);//程序执行时间
                $users=M('user')->field('user_id,user_recommend')->where('user_recommend > 0')->select();
                $childrenFile='Uploads/getChilds/'.date('Ymd').'-'.$id.'.txt';
                if(file_exists($childrenFile)){//判断更新缓存
                    $children=file_get_contents($childrenFile);
                    $login=unserialize($children);
                }else{
                    $arr[]=$id;
                    set_time_limit(120);//程序执行时间
                    $login=$this->getChilds($users,$id,$arr);
                    $childrenData=serialize($login);
                    file_put_contents($childrenFile,$childrenData);
                    //$this->ajaxReturn(array('status'=>0,'msg'=>'缓存信息已更新，请重新载入'));
                }
                $where='(CMD between 0 and 1) and (LOGIN in ('.implode(',',$login).')) ';
            }
            if($transaction_type==1){
                $where.=' and (right(SYMBOL,2) = \'bo\') ';
            }else if($transaction_type==2){
                $where.=' and (right(SYMBOL,2) <> \'bo\') ';
            }
            if(!empty($from) && !empty($to)){
                $where.=' and (CLOSE_TIME between \''.$from.' 00:00:00\' and \''.$to.' 23:59:59\') ';
            }
            $model=M('mt4_trades','','DB_CONFIG2');
            $reoups=$model->field('TICKET,LOGIN,OPEN_TIME,CMD,SYMBOL,VOLUME,OPEN_PRICE,SL,TP,CLOSE_TIME,CLOSE_PRICE,COMMISSION,SWAPS,PROFIT,COMMENT')
                ->where($where)->order('TICKET desc')->select();
            foreach ($reoups as $k => $v){
                $list[]=array(
                    'ticket'=>$v['ticket'],
                    'login'=>$v['login'],
                    'open_time'=>$v['open_time'],
                    'open_price'=>$v['open_price'],
                    'cmd'=>$v['cmd']==1 ? 'SELL' : 'BUY',
                    'symbol'=>$v['symbol'],
                    'volume'=>round($v['volume']/100,2),
                    'sl'=>$v['sl'],
                    'tp'=>$v['tp'],
                    'close_time'=>$v['close_time'],
                    'close_price'=>$v['close_price'],
                    'commission'=>$v['commission'],
                    'swaps'=>$v['swaps'],
                    'profit'=>round($v['profit'],2),
                    'comment'=>$v['comment']
                );
            }
        }
        $csv=new \Think\Csv();
        $csv_title=array('交易号','MT4','开单时间','开单价','交易类型','交易品种','交易量','SL','TP','关单时间','关单价','手续费','库存费','收益','注释');
        $csv->put_csv($list,$csv_title);
    }

    public function fundChange(){//资金变动
        $admin = session('admin');
        if(empty($admin)){echo "身份信息过期请重新登录";exit;}
        $id=I('id');
        if(!empty($id)){
            $type=I('type') ? I('type') : 0;
            $from=I('from') ? I('from') : 0;
            $to=I('to') ? I('to') : 0;
            $where='(CMD = 6) and (LOGIN = '.$id.') ';
            if($type==1){//入金
                $where.=' and (COMMENT like \'%deposit%\') ';
            }else if($type==2){//出金
                $where.=' and (COMMENT like \'%withdrawal%\') ';
            }else if($type==3){//内转
                $where.=' and (COMMENT like \'%InTurn%\') ';
            }else if($type==4){//返佣
                $where.=' and (COMMENT like \'%CommBo%\') ';
            }else if($type==5){//外佣
                $where.=' and (COMMENT like \'%CommFDHs#FDHs%\') ';
            }else if($type==6){//手续费
                $where.=' and (COMMENT like \'%COMMISSION%\') ';
            }
            if(!empty($from) && !empty($to)){
                $where.=' and (CLOSE_TIME between \''.$from.' 00:00:00\' and \''.$to.' 23:59:59\') ';
                $this->assign('from',$from);
                $this->assign('to',$to);
            }
            $model=M('mt4_trades','','DB_CONFIG2');
            $count=$model->where($where)->count();
            $Page = new \Think\Page($count,25);
            $Page->parameter['id']=$id;
            $Page->parameter['type']=$type;
            $Page->parameter['from']=$from;
            $Page->parameter['to']=$to;
            $show = $Page->show();
            $reoups=$model->field('TICKET,LOGIN,CMD,CLOSE_TIME,PROFIT,COMMENT')
                ->where($where)->order('TICKET desc')->limit($Page->firstRow.','.$Page->listRows)->select();
            $sum=$model->where($where)->sum('PROFIT');
            $this->assign('list',$reoups);
            $this->assign('page',$show);
            $this->assign('type',$type);
            $this->assign('id',$id);
            $this->assign('sum',$sum);
        }
        $this->display();
    }

    public function downloadFundChange(){//下载资金变动
        $admin = session('admin');
        if(empty($admin)){echo "身份信息过期请重新登录";exit;}
        $id=I('id');
        $list=[];
        if(!empty($id)){
            $type=I('type') ? I('type') : 0;
            $from=I('from') ? I('from') : 0;
            $to=I('to') ? I('to') : 0;
            $where='(CMD = 6) and (LOGIN = '.$id.') ';
            if($type==1){//入金
                $where.=' and (COMMENT like \'%deposit%\') ';
            }else if($type==2){//出金
                $where.=' and (COMMENT like \'%withdrawal%\') ';
            }else if($type==3){//内转
                $where.=' and (COMMENT like \'%InTurn%\') ';
            }else if($type==4){//返佣
                $where.=' and (COMMENT like \'%CommBo%\') ';
            }else if($type==5){//外佣
                $where.=' and (COMMENT like \'%CommFDHs#FDHs%\') ';
            }else if($type==6){//手续费
                $where.=' and (COMMENT like \'%COMMISSION%\') ';
            }
            if(!empty($from) && !empty($to)){
                $where.=' and (CLOSE_TIME between \''.$from.' 00:00:00\' and \''.$to.' 23:59:59\') ';
            }
            $model=M('mt4_trades','','DB_CONFIG2');
            $reoups=$model->field('TICKET,LOGIN,CMD,CLOSE_TIME,PROFIT,COMMENT')->where($where)->order('TICKET desc')->select();
            foreach ($reoups as $k => $v){
                $list[]=array(
                    'ticket'=>$v['ticket'],
                    'login'=>$v['login'],
                    'cmd'=>$v['cmd']==6 ? 'Balance' : $v['cmd'],
                    'close_time'=>$v['close_time'],
                    'profit'=>round($v['profit'],2),
                    'comment'=>$v['comment']
                );
            }
        }
        $csv=new \Think\Csv();
        $csv_title=array('交易号','MT4','交易类型','发放时间','收益','注释');
        $csv->put_csv($list,$csv_title);
    }

    public function onWay(){//在途订单
        $admin = session('admin');
        if(empty($admin)){echo "身份信息过期请重新登录";exit;}
        $login=I('id');
        if(!empty($login)){
            $from=I('from') ? I('from') : 0;
            $to=I('to') ? I('to') : 0;
            $type=I('type') ? I('type') : 0;
            $where='(LOGIN = '.$login.') and (UNIX_TIMESTAMP(CLOSE_TIME) = 0) ';
            if($type==1){
                $where.=' and (CMD = 1)';
            }else if($type==2){
                $where.=' and (CMD = 0)';
            }else{
                $where.=' and (CMD between 0 and 1)';
            }
            if(!empty($from)&&!empty($to)){
                $where.=' and (OPEN_TIME between \''.$from.' 00:00:00\' and \''.$to.' 23:59:59\') ';
                $this->assign('from',$from);
                $this->assign('to',$to);
            }
            $model=M('mt4_trades','','DB_CONFIG2');
            $count=$model->where($where)->count();
            $Page = new \Think\Page($count,25);
            $Page->parameter['type']=$type;
            $Page->parameter['from']=$from;
            $Page->parameter['to']=$to;
            $show = $Page->show();
            $reoups=$model->field('TICKET,LOGIN,OPEN_TIME,CMD,SYMBOL,VOLUME,OPEN_PRICE,SL,TP,CLOSE_TIME,CLOSE_PRICE,COMMISSION,SWAPS,PROFIT,COMMENT')
                ->where($where)->order('TICKET desc')->limit($Page->firstRow.','.$Page->listRows)->select();
            $this->assign('list',$reoups);
            $this->assign('page',$show);
            $this->assign('id',$login);
            $this->assign('type',$type);
        }
        $this->display();
    }

    public function profitLog(){//余额宝收益
        $admin = session('admin');
        if(empty($admin)){echo "身份信息过期请重新登录";exit;}
        $login=I('id') ? I('id') : 0;
        $from=I('from') ? I('from') : 0;
        $to=I('to') ? I('to') : 0;
        $status=I('status') ? I('status') : 0;
        $where='';
        if(!empty($login)){
            $where='(user_id in ('.$login.')) ';
        }
        if(!empty($status)){
            if($status==1){
                if(empty($where)){
                    $where.=' (status = 1)';
                }else{
                    $where.=' and (status = 1)';
                }
            }else{
                if(empty($where)){
                    $where.=' (status <> 1)';
                }else{
                    $where.=' and (status <> 1)';
                }
            }
        }
        if(!empty($from)&&!empty($to)){
            if(empty($where)){
                $where.=' (`date` between \''.$from.'\' and \''.$to.'\') ';
            }else{
                $where.=' and (`date` between \''.$from.'\' and \''.$to.'\') ';
            }
            $this->assign('from',$from);
            $this->assign('to',$to);
        }
        $model=M('profit');
        if(empty($where)){
            $count=$model->count();
        }else{
            $count=$model->where($where)->count();
        }
        $Page = new \Think\Page($count,25);
        $Page->parameter['id']=$login;
        $Page->parameter['status']=$status;
        $Page->parameter['from']=$from;
        $Page->parameter['to']=$to;
        $show = $Page->show();
        if(empty($where)){
            $list=$model->field('id,user_id,balance,profit,rate,date,time,status')->order('id desc')->limit($Page->firstRow.','.$Page->listRows)->select();
        }else{
            $list=$model->field('id,user_id,balance,profit,rate,date,time,status')->where($where)->order('id desc')->limit($Page->firstRow.','.$Page->listRows)->select();
        }
        $this->assign('list',$list);
        $this->assign('page',$show);
        $this->assign('id',$login);
        $this->assign('status',$status);
        $this->display();
    }

    public function redistribute(){//余额宝-重新发放
        $id=I('post.id') ? I('post.id') : die(json_encode(array('status'=>0,'msg'=>'非法操作')));
        $model=M('profit');
        $msg=$model->field('user_id,profit')->where(['id'=>$id])->find();
        $model->startTrans();
        $res=$model->where(['id'=>$id])->save(['status'=>1]);
        if($res){
            $request = "action=changebalance&login=".$msg['user_id']."&value=".$msg['profit']."&comment=balance#profit ".date('Y-m-d')."\0";//bulkchangebalance-批量修改bulk
            $return=mt4_operation($request);
            parse_str($return,$res1);
            if($res1['result']==1){
                $model->commit();
                //$balance=explode(';',$res['size']);$balance[1]
                $this->ajaxReturn(array('status'=>1,'msg'=>'操作成功'));
            }else{
                $model->rollback();
                $this->ajaxReturn(array('status'=>0,'msg'=>'操作失败'));
            }
        }else{
            $this->ajaxReturn(array('status'=>0,'msg'=>'操作失败'));
        }
    }
}